<?php
namespace App\Service\ApiXcx;

use Illuminate\Support\Facades\DB;

class PointsOrderService extends BaseService
{
    //订单

    /**
     * 列表
     * @param int $uid 用户ID
     * @param int $status 0所有，1待付款，2待发货，3待收货，4完成
     * @param array $pages【start，limit】
     */
    public function getList($uid, $pages, $status = 0)
    {
        $this->autoAccept($uid);
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = DB::table($this->dbPointsOrder);
        $ws[] = ['del', '=', 0];
        $ws[] = ['uid', '=', $uid];
        if ($status > 0) {
            if ($status == 1) {
                $ws[] = ['iscancel', '=', 1];
                $ws[] = ['status', '=', 1];
                $db = $db->where($ws);
            } else if ($status == 2) {
                $ws[] = ['iscancel', '=', 1];
                $ws[] = ['delivery', '=', 1];
                $ws[] = ['status', '=', 2];
                $db = $db->where($ws);
            } else if ($status == 3) {
                $ws[] = ['iscancel', '=', 1];
                $w1s = $ws; $w2s = $ws;
                $w1s[] = ['delivery', '=', 1];
                $w1s[] = ['status', '=', 3];
                $w2s[] = ['delivery', '=', 2];
                $w2s[] = ['status', '=', 2];
                $db = $db->where($w1s)->orWhere($w2s);
            } else if ($status == 4) {
                $w1s = $ws; $w2s = $ws; $w3s = $ws;
                $w1s[] = ['iscancel', '=', 1];
                $w1s[] = ['delivery', '=', 1];
                $w1s[] = ['status', '=', 4];
                $w2s[] = ['iscancel', '=', 1];
                $w2s[] = ['delivery', '=', 2];
                $w2s[] = ['status', '=', 3];
                $w3s[] = ['iscancel', '>', 1];
                $db = $db->where($w1s)->orWhere($w2s)->orWhere($w3s);
            }
        } else {
            $db = $db->where($ws);
        }
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return array('code' => 0, 'msg' => '没有订单', 'data'=> [], 'total' => 0);
        }
        $status1s = $this->orderStatus1s;
        $status2s = $this->orderStatus2s;
        $cancels = $this->orderCancels;
        $deliverys = $this->orderDeliverys;
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            //下单时间
            $ordertime = strtotime($v['addtime']);
            //订单状态
            if ($v['iscancel'] > 1) {
                $status_name = array_key_exists($v['iscancel'], $cancels) ? $cancels[$v['iscancel']] : '';
            } else if ($v['delivery'] == 1) {
                $status_name = array_key_exists($v['status'], $status1s) ? $status1s[$v['status']] : '';
            } else {
                $status_name = array_key_exists($v['status'], $status2s) ? $status2s[$v['status']] : '';
            }
            //商品图片
            $gArys = [];
            $osOnes = DB::table($this->dbPointsOsku)->where('order_id', $v['id'])->get();
            if (count($osOnes)) {
                $gids = [];
                foreach ($osOnes as $osOne) {
                    $imgOne = (array) DB::table($this->dbPointsGimg)
                        ->where('del', 0)
                        ->where('gid', $osOne->gid)
                        ->first();
                    $gOne = (array) DB::table($this->dbPointsGoods)
                        ->where('del', 0)
                        ->where('id', $osOne->gid)
                        ->first();
                    if (!in_array($osOne->gid, $gids) && !empty($imgOne) && !empty($gOne)) {
                        $gArys[] = [
                            'gid' => $osOne->gid,
                            'sku_id' => $osOne->sku_id,
                            'gname' => $gOne['title'],
                            'gimg' => env('DOMAIN') . '/' . $imgOne['link'],
                            'sku_name' => $osOne->sku_name,
                        ];
                        $gids[] = $osOne->gid;
                    }
                }
            }
            //配送信息
            $delivery_name = array_key_exists($v['delivery'], $deliverys) ? $deliverys[$v['delivery']] : '';
            //门店信息
            $shopOne = (array) DB::table($this->dbShop)->where('del', 0)->where('id', $v['shop_id'])->first();
            $shopName = empty($shopOne) ? '' : $shopOne['shop_name'] . '-' . $shopOne['address'];
            $arys[] = [
                'id' => $v['id'],
                'orderno' => $v['orderno'],
                'ordertime' => date('Y-m-d H:i', $ordertime),
                'status' => $v['status'],
                'status_name' => $status_name,
                'iscancel' => $v['iscancel'],
                //'cancel_name' => $cancel_name,
                'wuliu' => $v['wuliu'],
                'wuliuhao' => $v['wuliuhao'],
                'goodsList' => $gArys,
//                'priceTotal' => toNumber($v['price']),
                'priceTotal' => $v['price'],
                'priceLine' => toNumber($v['price_line']),
                'num' => $v['num'],
                'delivery' => $v['delivery'],
                'delivery_name' => $delivery_name,
                'shop_id' => $v['shop_id'],
                'shop_name' => $shopName,
                'uid' => $uid,
                'tradeno' => $v['tradeno'],
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data'=> $arys, 'total' => $total);
    }

    //下单前选项
    public function getOption()
    {
        $arys = [];
        //配送方式
        $deliverys = $this->orderDeliverys;
        foreach ($deliverys as $k => $v) {
            $arys['delivery'][] = [
                'id' => $k,
                'title' => $v,
            ];
        }
        //选择门店
        $shopOnes = DB::table($this->dbShop)->where('del', 0)->get();
        if (count($shopOnes)) {
            foreach ($shopOnes as $v) {
                $v = (array) $v;
                $arys['shop'][] = [
                    'id' => $v['id'],
                    'title' => $v['shop_name'],
                    'map' => $v['map'],
                ];
            }
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }

    /**
     * 下单选项
     * @param array $$pas【sku_id、shop_id、delivery_id、num】
     */
    public function orderOption($sku_id, $shop_id, $delivery_id, $num)
    {
        $arys = ['sku'=>[], 'shop'=>[], 'delivery'=>[]];
        //商品信息
        $skuOne = (array) DB::table($this->dbPointsGsku)->where('id', $sku_id)->first();
        if (!empty($skuOne)) {
            $gOne = (array) DB::table($this->dbPointsGoods)->where('id', $skuOne['gid'])->first();
            $gname = empty($gOne) ? '' : $gOne['title'];
            $gimg = empty($gOne) ? '' : env('DOMAIN') . '/' . $gOne['bigimg'];
            $arys['sku'] = [
                'sku_id' => $sku_id,
                'sku_name' => $skuOne['title'],
                'sku_price' => $skuOne['price'],
                'price_line' => $skuOne['price_line']/100,
                'sku_num' => $num,
                'gname' => $gname,
                'gimg' => $gimg,
            ];
        }
        //门店信息
        $shopOne = (array) DB::table($this->dbShop)->where('id', $shop_id)->first();
        if (!empty($shopOne)) {
            $arys['shop'] = [
                'shop_id' => $shop_id,
                'shop_name' => $shopOne['shop_name'] . '(' . $shopOne['address'] . ')',
            ];
        }
        //配送信息
        $deliverys = $this->orderDeliverys;
        $arys['delivery'] = [
            'delivery_id' => $delivery_id,
            'delivery_name' => array_key_exists($delivery_id, $deliverys) ? $deliverys[$delivery_id] : '',
        ];
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }

    /**
     * 直接下单
     * @param array $pas
     */
    public function addByGid($pas)
    {
        //用户信息
        $uOne = (array) DB::table($this->dbUser)
            ->where('id', $pas['uid'])
            ->first();
        if (empty($uOne)) {
            return array('code' => -2, 'msg' => '用户不存在');
        }
        //收货地址
        $addressOne = (array) DB::table($this->dbAddress)
            ->where('del', 0)
            ->where('uid', $pas['uid'])
            ->where('id', $pas['address_id'])
            ->first();
        if (empty($addressOne)) {
            return array('code' => -2, 'msg' => '收货地址不存在');
        }
        //SKU信息
        $skuOne = (array) DB::table($this->dbPointsGsku)
            ->where('del', 0)
            ->where('id', $pas['sku_id'])
            ->first();
        if (empty($skuOne)) {
            return array('code' => -2, 'msg' => '规格为空');
        }
        if ($pas['num'] > $skuOne['stock']) {
            return array('code' => -2, 'msg' => '规格库存不足');
        }
        //商品信息
        $gOne = (array) DB::table($this->dbPointsGoods)
            ->where('del', 0)
            ->where('id', $skuOne['gid'])
            ->first();
        if (empty($gOne)) {
            return array('code' => -2, 'msg' => '商品为空');
        }

        //订单信息
        $orderno = toOrderno();
        $priceTotal = $real_pay = $skuOne['price']  * $pas['num'];
        if($uOne['points'] < $priceTotal){
            return array('code' => -2, 'msg' => '积分不足');
        }
        $priceLineTotal = $skuOne['price_line']  * $pas['num'];
        $orderData = [
            'from_type' => 2,
            'uid' => $pas['uid'],
            'uname' => $uOne['nickname'],
            'orderno' => $orderno,
            'tradeno' => toTradeno(),
            'address_id' => $pas['address_id'],
            'delivery' => $pas['delivery'],
            'shop_id' => $pas['shop_id'],
            'price' => $priceTotal,
            'price_line' => $priceLineTotal,
            'real_pay' => $real_pay,
            'num' => $pas['num'],
            'status' => 2,
            'remark' => $pas['remark'],
            'addtime' => toDate(),
        ];
        DB::beginTransaction(); //开启事务
        try {
            //订单添加
            $orderid = DB::table($this->dbPointsOrder)->insertGetId($orderData);
            if (!$orderid) {
                return array('code'=>-1, 'msg'=>'下单失败');
            }
            //SKU信息
            $skuAry = [
                'order_id' => $orderid,
                'gid' => $skuOne['gid'],
                'sku_id' => $pas['sku_id'],
                'gname' => $gOne['title'],
                'sku_name' => $skuOne['title'],
                'gimg' => $gOne['bigimg'],
                'price' => $skuOne['price'],
                'num' => $pas['num'],
                'delivery' => $pas['delivery'],
                'addtime' => toDate(),
            ];
            //订单SKU
            $osid = DB::table($this->dbPointsOsku)->insertGetId($skuAry);
            if (!$osid) {
                return array('code'=>-1, 'msg'=>'订单SKU失败');
            }
            //更新库存
            $skuData = [
                'stock' => $skuOne['stock'] - $pas['num'],
                'uptime' => toDate()
            ];
            $skuUp = DB::table($this->dbPointsGsku)->where('id', $pas['sku_id'])->update($skuData);
            if (!$skuUp) {
                return array('code'=>-2, 'msg'=>'减库存失败');
            }
            //更新销量
            $this->dbConn($this->dbPointsGoods)->where('id', $gOne['id'])
                ->update(['sale' => $gOne['sale'] + $pas['num']]);
            //处理积分
            $point_log = [
                'uid' => $uOne['id'],
                'type' => 2,
                'before_points' => $uOne['points'],
                'operator' => '-',
                'change_points' => $priceTotal,
                'after_points' => ($uOne['points'] - $priceTotal),
                'reason' => '下单扣积分',
                'relation_value' => $orderno,
                'addtime' => toDate()
            ];
            DB::table($this->dbUserPointLog)->insertGetId($point_log);
            DB::table($this->dbUser)->where('id', $uOne['id'])->decrement('points', $priceTotal);
            //返回的参数
            $arys = [
                'orderno' => $orderno,
            ];
            DB::commit(); //提交事务
            return array('code'=>0, 'msg'=>'success', 'data' => $arys);
        } catch (\Exception $e) {
            DB::rollBack(); //事务回滚
            echo $e->getMessage();
            return array('code' => -1, 'msg' => '操作失败');
        }
    }

    /**
     * 订单取消
     * @param int $id 订单ID
     */
    public function setCancel($id)
    {
        $res = (array) DB::table($this->dbPointsOrder)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '该订单不存在');
        }
        if ($res['iscancel'] == 2) {
            return array('code' => -2, 'msg' => '该订单在审核中');
        }
        if ($res['iscancel'] == 3) {
            return array('code' => -2, 'msg' => '该订单已取消');
        }
        $status = $res['status']<2 ? 3 : 2; //待付款不用审核，已付款要审核
        $up = DB::table($this->dbPointsOrder)->where('id', $id)
            ->update(['iscancel' => $status, 'canceltime' => toDate()]);
        if (!$up) {
            return array('code' => -1, 'msg' => '操作失败');
        }

        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * 订单撤回
     * @param int $id 订单ID
     */
    public function setRevoke($id)
    {
        $res = (array) DB::table($this->dbPointsOrder)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '该订单不存在');
        }
        if ($res['iscancel'] == 1) {
            return array('code' => -2, 'msg' => '该订单未申请');
        }
        if ($res['iscancel'] > 2) {
            return array('code' => -2, 'msg' => '该订单已审核');
        }
        $up = DB::table($this->dbPointsOrder)->where('id', $id)
            ->update(['iscancel' => 1]);
        if (!$up) {
            return array('code' => -1, 'msg' => '操作失败');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * 订单
     * @param int $id 订单ID
     */
    public function setFinish($id)
    {
        $res = (array) DB::table($this->dbPointsOrder)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '该订单不存在');
        }
        if ($res['status'] < 4) {
            return array('code' => -2, 'msg' => '该订单未签收');
        }
        if ($res['status'] == 5) {
            return array('code' => -2, 'msg' => '该订单已完成');
        }
        $up = DB::table($this->dbPointsOrder)->where('id', $id)
            ->update(['status' => 5, 'finishtime' => toDate()]);
        if (!$up) {
            return array('code' => -1, 'msg' => '操作失败');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    //再来一单
    public function again($id)
    {
        //老的订单
        $oldOne = (array) DB::table($this->dbPointsOrder)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($oldOne)) {
            return array('code' => -2, 'msg' => '该订单不存在');
        }
        //用户信息
        $uOne = (array) DB::table($this->dbUser)
            ->where('id', $oldOne['uid'])
            ->first();
        if (empty($uOne)) {
            return array('code' => -2, 'msg' => '用户不存在');
        }
        //老的SKU
        $skuOlds = DB::table($this->dbPointsOsku)->where('order_id', $oldOne['id'])->get();
        if (!count($skuOlds)) {
            return array('code' => -2, 'msg' => '该订单信息不存在');
        }
        if($uOne['points'] < $oldOne['price']){
            return array('code' => -2, 'msg' => '积分不足');
        }
        DB::beginTransaction(); //开启事务
        try {
            //生成订单
            $orderno = toOrderno();
            $price = $oldOne['price'];
            $orderData = [
                'uid' => $oldOne['uid'],
                'uname' => $oldOne['uname'],
                'orderno' => $orderno,
                'tradeno' => toTradeno(),
                'address_id' => $oldOne['address_id'],
                'delivery' => $oldOne['delivery'],
                'shop_id' => $oldOne['shop_id'],
                'price' => $price,
                'price_line' => $oldOne['price_line'],
                'real_pay' => $oldOne['real_pay'],
                'num' => $oldOne['num'],
                'status' => 2,
                'remark' => $oldOne['remark'],
                'again_id' => $oldOne['id'],
                'addtime' => toDate(),
            ];
            $orderid = DB::table($this->dbPointsOrder)->insertGetId($orderData);
            if (!$orderid) {
                return array('code' => -1, 'msg' => '再来一单失败');
            }

            //生成SKU
            foreach ($skuOlds as $v) {
                $v = (array) $v;
                $gArys = [
                    'order_id' => $orderid,
                    'gid' => $v['gid'],
                    'sku_id' => $v['sku_id'],
                    'gname' => $v['gname'],
                    'sku_name' => $v['sku_name'],
                    'gimg' => $v['gimg'],
                    'price' => $v['price'],
                    'num' => $v['num'],
                    'delivery' => $v['delivery'],
                    'addtime' => toDate(),
                ];
                $osid = DB::table($this->dbPointsOsku)->insertGetId($gArys);
                if (!$osid) {
                    return array('code'=>-1, 'msg'=>'订单SKU失败');
                }
                //减库存更新
                $skuOne = (array) DB::table($this->dbPointsGsku)->where('id', $v['sku_id'])->first();
                if (empty($skuOne)) {
                    return array('code'=>-2, 'msg'=>'商品SKU失败');
                }
                if ($skuOne['stock'] < $v['num']) {
                    return array('code'=>-2, 'msg'=>'商品SKU不足');
                }
                $stockNew = $skuOne['stock'] - $v['num'];
                $skuData = [
                    'stock' => $stockNew,
                    'uptime' => toDate()
                ];
                if ($stockNew == 0) {
                    $skuData['del'] = 1;
                    $skuData['deltime'] = toDate();
                }
                $skuUp = DB::table($this->dbPointsGsku)->where('id', $v['sku_id'])->update($skuData);
                if (!$skuUp) {
                    return array('code'=>-2, 'msg'=>'减库存失败');
                }
                //更新销量
                $gOne = (array) $this->dbConn($this->dbPointsGoods)->where('id', $v['gid'])->first();
                if (!empty($gOne)) {
                    $this->dbConn($this->dbPointsGoods)->where('id', $v['gid'])
                        ->update(['sale' => $gOne['sale'] + $v['num']]);
                }
            }
            //处理积分
            $point_log = [
                'uid' => $uOne['id'],
                'type' => 2,
                'before_points' => $uOne['points'],
                'operator' => '-',
                'change_points' => $price,
                'after_points' => ($uOne['points'] - $price),
                'reason' => '下单扣积分',
                'relation_value' => $orderno,
                'addtime' => toDate()
            ];
            DB::table($this->dbUserPointLog)->insertGetId($point_log);
            DB::table($this->dbUser)->where('id', $uOne['id'])->decrement('points', $price);
            $resData = [
                'orderid' => $orderid,
            ];
            DB::commit(); //提交事务
            return array('code'=>0, 'msg'=>'success', 'data' => $resData);
        } catch (\Exception $e) {
            DB::rollBack(); //事务回滚
            echo $e->getMessage();
            return array('code' => -1, 'msg' => '操作失败');
        }
    }

    //订单详情
    public function getOne($id)
    {
        //订单
        $resOne = (array) DB::table($this->dbPointsOrder)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($resOne)) {
            return array('code' => -2, 'msg' => '该订单不存在');
        }
        //SKU
        $skuOnes = DB::table($this->dbPointsOsku)->where('order_id', $resOne['id'])->get();
        if (!count($skuOnes)) {
            return array('code' => -2, 'msg' => '该订单信息不存在');
        }
        //状态
        $cancels = $this->orderCancels;
        $status1s = $this->orderStatus1s;
        $status2s = $this->orderStatus2s;
        if ($resOne['iscancel'] > 1) {
            $status_name = array_key_exists($resOne['iscancel'], $cancels) ? $cancels[$resOne['iscancel']] : '';
        } else if ($resOne['delivery'] == 1) {
            $status_name = array_key_exists($resOne['status'], $status1s) ? $status1s[$resOne['status']] : '';
        } else {
            $status_name = array_key_exists($resOne['status'], $status2s) ? $status2s[$resOne['status']] : '';
        }
        //收货地址
        $addressOne = (array) DB::table($this->dbAddress)->where('id', $resOne['address_id'])->first();
        $street = empty($addressOne) ? '' : $addressOne['wx_door'];
        $door = empty($addressOne) ? '' : $addressOne['door'];
        $addressList = [
            'dizhi' => $street . $door,
            'phone' => empty($addressOne) ? '' : $addressOne['phone'],
            'accepter' => empty($addressOne) ? '' : $addressOne['accepter'],
        ];
        //商品信息
        $goodsList = [];
        $osOnes = DB::table($this->dbPointsOsku)->where('order_id', $resOne['id'])->get();
        if (count($osOnes)) {
            $gids = [];
            foreach ($osOnes as $osOne) {
                $imgOne = (array) DB::table($this->dbPointsGimg)
                    ->where('del', 0)
                    ->where('gid', $osOne->gid)
                    ->first();
                $gOne = (array) DB::table($this->dbPointsGoods)
                    ->where('del', 0)
                    ->where('id', $osOne->gid)
                    ->first();
                if (!in_array($osOne->gid, $gids) && !empty($imgOne) && !empty($gOne)) {
                    $goodsList[] = [
                        'gid' => $osOne->gid,
                        'sku_id' => $osOne->sku_id,
                        'gname' => $gOne['title'],
                        'gimg' => env('DOMAIN') . '/' . $imgOne['link'],
                        'sku_name' => $osOne->sku_name,
                        'sku_num' => $osOne->num,
                        'sku_price' => $osOne->price / 100,
                    ];
                    $gids[] = $osOne->gid;
                }
            }
        }
        $priceTotal = $resOne['price'];
        //支付方式
        $payWayName = '积分支付';
        //门店信息
        $shopOne = (array) DB::table($this->dbShop)->where('id', $resOne['shop_id'])->first();
        $shopList['address'] = empty($shopOne) ? '' : $shopOne['address'];
        $shopList['phone'] = empty($shopOne) ? '' : $shopOne['phone'];
        $shopList['map_lat'] = ''; //维度
        $shopList['map_lon'] = ''; //经度
        if (!empty($shopOne) && $shopOne['map']) {
            $maps = explode(',', $shopOne['map']);
            $shopList['map_lat'] = (float) $maps[0];
            $shopList['map_lon'] = (float) $maps[1];
        }
        $arys = [
            'id' => $resOne['id'],
            'status' => $resOne['status'],
            'statusName' => $status_name,
            'wuliu' => $resOne['wuliu'],
            'wuliuhao' => $resOne['wuliuhao'],
            'sendtime' => $resOne['sendtime'],
            'addressList' => $addressList,
            'goodsList' => $goodsList,
            'priceTotal' => $priceTotal,
            'realPay' => $resOne['real_pay'],
            'price_line' => $resOne['price_line']/100,
            'ordertime' => $resOne['addtime'],
            'orderno' => $resOne['orderno'],
            'payWay' => $resOne['pay_way'],
            'payWayName' => $payWayName,
            'payno' => '',
            'delay' => 1, //订单超时时间，分钟
            'delivery' => $resOne['delivery'],
            'shopList' => $shopList,
            'iscancel' => $resOne['iscancel'],
            'remark' => $resOne['remark'],
            'tradeno' => $resOne['tradeno'],
        ];
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }

//    //状态发货
//    public function sendOut($id)
//    {
//        $oldOne = (array) DB::table($this->dbOrder)
//            ->where('del', 0)
//            ->where('id', $id)
//            ->first();
//        if (empty($oldOne)) {
//            return $this->toback(-2, '该订单不存在');
//        }
//        if ($oldOne['delivery'] == 2) {
//            return $this->toback(-2, '该订单属于自提，不需要发货');
//        }
//        if ($oldOne['iscancel'] > 1) {
//            return $this->toback(-2, '该订单处于取消流程中');
//        }
//        if ($oldOne['status'] != 2) {
//            return $this->toback(-2, '该订单状态错误');
//        }
//        $up = DB::table($this->dbOrder)->where('id', $id)->update([
//            'status' => 3, 'sendtime' => toDate(),
//        ]);
//        if (!$up) {
//            return $this->toback(-2, '设置失败');
//        }
//        return $this->toback(0, 'success');
//    }

    //状态收货
    public function receive($id)
    {
        $order_info = (array) DB::table($this->dbPointsOrder)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($order_info)) {
            return $this->toback(-2, '该订单不存在');
        }
        if ($order_info['delivery'] == 2) {
            return $this->toback(-2, '该订单属于自提');
        }
        if ($order_info['iscancel'] > 1) {
            return $this->toback(-2, '该订单处于取消流程中');
        }
        if ($order_info['status'] != 3) {
            return $this->toback(-2, '该订单状态错误');
        }

        DB::beginTransaction(); //开启事务
        try {
            DB::table($this->dbPointsOrder)->where('id', $id)->update([
                'status' => 4, 'finishtime' => toDate(),
            ]);
            DB::commit(); //提交事务
            return $this->toback(0, 'success');
        } catch (\Exception $e) {
            DB::rollBack(); //事务回滚
            echo $e->getMessage();
            return array('code' => -1, 'msg' => '操作失败');
        }
    }

    //状态自提
    public function pickup($id)
    {
        $order_info = (array) DB::table($this->dbPointsOrder)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($order_info)) {
            return $this->toback(-2, '该订单不存在');
        }
        if ($order_info['delivery'] == 1) {
            return $this->toback(-2, '该订单属于快递');
        }
        if ($order_info['iscancel'] > 1) {
            return $this->toback(-2, '该订单处于取消流程中');
        }
        if ($order_info['status'] != 2) {
            return $this->toback(-2, '该订单状态错误');
        }

        DB::beginTransaction(); //开启事务
        try {
            DB::table($this->dbPointsOrder)->where('id', $id)->update([
                'status' => 3, 'finishtime' => toDate(),
            ]);
            DB::commit(); //提交事务
            return $this->toback(0, 'success');
        } catch (\Exception $e) {
            DB::rollBack(); //事务回滚
            echo $e->getMessage();
            return array('code' => -1, 'msg' => '操作失败');
        }
    }

    //交易流水号初始化
    public function tradeno()
    {
        $res = $this->dbConn($this->dbPointsOrder)
            ->where('del', 0)
            ->where('tradeno', '')
            ->get();
        if (empty($res)) {
            return false;
        }
        foreach ($res as $v) {
            $v = (array) $v;
            $tradeno = date('YmdHis', strtotime($v['addtime'])) . rand(1000000000, 9999999999);
            $this->dbConn($this->dbPointsOrder)->where('id', $v['id'])
                ->update(['tradeno' => $tradeno]);
        }
        return true;
    }

    //发货20天后自动确认收货
    public function autoAccept($uid = 0)
    {
        $day20 = date('Y-m-d H:i:s', strtotime('-20 days'));
        $db = $this->dbConn($this->dbPointsOrder)
            ->where('del', 0)
            ->where('iscancel', 1)
            ->where('status', 3);
        if ($uid) {
            $db = $db->where('uid', $uid);
        }
        $db->where('sendtime', '<=', $day20)
            ->update(['status' => 4, 'finishtime' => toDate()]);
        return true;
//        $res = (array) $db->where('sendtime', '<=', $day20)
//            ->orderBy('id', 'desc')->first();
//        ddd($res);
    }
}